package com.blueberry.commbank.application.impl;

import com.blueberry.commbank.application.TransferService;
import com.blueberry.commbank.application.dto.TransferRequestDTO;
import com.blueberry.commbank.domain.entity.Account;
import com.blueberry.commbank.domain.entity.Money;
import com.blueberry.commbank.domain.service.AccountTransferService;
import com.blueberry.commbank.repository.AccountRepository;
import java.util.Currency;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class TransferServiceImpl implements TransferService {
    @Autowired
    private AccountTransferService accountTransferService;
    @Autowired
    private AccountRepository accountRepository;

    @Transactional
    @Override
    public void transfer(TransferRequestDTO transferRequestDTO) {
        Money targetMoney = new Money(transferRequestDTO.getMoney(),
                Currency.getInstance(transferRequestDTO.getTargetCurrency()));

        Account sourceAccount = accountRepository.find(transferRequestDTO.getSourceAccountNum());
        Account targetAccount = accountRepository.find(transferRequestDTO.getTargetAccountNum());

        accountTransferService.transfer(sourceAccount, targetAccount, targetMoney);

        accountRepository.save(sourceAccount);
        accountRepository.save(targetAccount);
    }
}
